﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace AbstractLabs.PowerShell.Twitter
{
    [Cmdlet(VerbsCommon.Set, "TwitterAuthorization")]
    public class AuthorizationCmdlet : Cmdlet
    {
        protected override void BeginProcessing()
        {
            base.BeginProcessing();
            try
            {
                OAuthConsumerContext context = new OAuthConsumerContext();
                context.ConsumerKey = Properties.Settings.Default.ConsumerKey;
                context.ConsumerSecret = Properties.Settings.Default.ConsumerSecret;
                context.SignatureMethod = SignatureMethod.HmacSha1;
                OAuthSession session = new OAuthSession(context, "https://twitter.com/oauth/request_token", "https://twitter.com/oauth/authorize", "https://twitter.com/oauth/access_token");
                IToken token = session.GetRequestToken();
                string authorizationLink = session.GetUserAuthorizationUrlForToken(token);
                Process.Start(authorizationLink);
                Console.WriteLine(String.Format("Pin Access Url:{0}", authorizationLink));
                Console.Write("Enter Pin:");
                string pin = Console.ReadLine();
                Properties.Settings.Default.Token = (TokenBase)session.ExchangeRequestTokenForAccessToken(token, pin);
                Properties.Settings.Default.Save();
                Console.WriteLine("Access token has been set successfully");
            }
            catch (Exception exception)
            {
                ThrowTerminatingError(new ErrorRecord(exception, String.Empty, ErrorCategory.WriteError, null));
            }
            
        }

    }
}
